﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.Caching;
using System.Xml;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Net;
using System.IO;
using System.Text;
using DDNY.WebPortals.Common;

/// <summary>
/// Summary description for LiveHelper
/// </summary>
public class LiveHelper
{
    public const string TrendsCacheKey = "TrendsCacheKeyLive";

    public const string ExtremeMoversCacheKey = "ExtremeMoversCacheKey";


    public const string LiveNewsFeedUrl = "http://api.bing.com/rss.aspx?Source=News&Market=en-WW&Version=2.0&Query={0}";
    public const string BingSearchFeedFormatString = "http://api.bing.com/rss.aspx?Source=Web&Version=2.0&Query={0}";
    public const string LiveSearchFeedUrl = "http://search.live.com/results.aspx?q={0}&go=&form=QBLH&format=rss";
    public const string LiveXrankFeedUrl = @"http://search.live.com/xrank/results.aspx?q=&p1=[GenericXRankAnswer+ScopeLink%3d%221%22+EntityType%3d%22homepage%22]&wf=XRankListEntity&FORM=X9X2&format=rss";

    public const string LiveXrankExtremeMoversUrl = @"http://search.live.com/xrank/results.aspx?q=&p1=[GenericXRankAnswer+EntityType%3d%22xrankeverything%22+ScopeLink%3d%221%22]&FORM=X9X1";

    public static List<string> GetExtremeMovers()
    {
        Cache cache = HttpContext.Current.Cache;
        List<string> result = null;
        if (cache[ExtremeMoversCacheKey] == null)
        {
            result = LoadExtremeMovers();
            cache.Add(ExtremeMoversCacheKey, result, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

        }
        else
        {
            result = cache[ExtremeMoversCacheKey] as List<string>;
        }
        return result;
    }

    private static List<string> LoadExtremeMovers()
    {
        Cache cache = HttpContext.Current.Cache;
        List<string> result = new List<string>();
        XmlDocument doc = new XmlDocument();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://www.live.com/?scope=web&mkt=en-US&setlang=SET_NULL&uid=12765715&FORM=W5WA");
        CookieContainer cookieContainer = new CookieContainer();
        request.CookieContainer = cookieContainer;
        request.GetResponse();
        HttpWebRequest xrankRequest = (HttpWebRequest)WebRequest.Create(LiveXrankExtremeMoversUrl);
        xrankRequest.CookieContainer = cookieContainer;
        WebResponse xrankResponse = xrankRequest.GetResponse();

        Encoding enc = Encoding.UTF8; // Windows default Code Page
        StreamReader loResponseStream = new StreamReader(xrankResponse.GetResponseStream(), enc);
        string xrankString = loResponseStream.ReadToEnd();
        string regexForAnchorText = @"(<a.*?>.*?</a>)";
        Regex regex = new Regex(regexForAnchorText);
        MatchCollection matches = regex.Matches(xrankString);
        foreach (Match item in matches)
        {
            if (item.Value.Contains("/xrank/results.aspx?q=") && !item.Value.Contains("/xrank/results.aspx?q=&amp;"))
            {
                string keyword = Regex.Replace(item.Value, @"\s*<.*?>\s*", "", RegexOptions.Singleline);




                bool IsKeyWordAllowed = GoogleHelper.CheckKeyWordAllowed(keyword);
                if (IsKeyWordAllowed)
                {
                    TextInfo UsaTextInfo = new CultureInfo("en-US", false).TextInfo;

                    string capitalized = UsaTextInfo.ToTitleCase(keyword);
                    result.Add(capitalized);
                    GoogleHelper.AddToTrendsArchive(capitalized);
                }
            }
        }
        return result;

    }


    public static List<string> GetTrendWords()
    {
        Cache cache = HttpContext.Current.Cache;
        List<string> result = null;
        if (cache[TrendsCacheKey] == null)
        {
            result = new List<string>();
            List<string> extremeMovers = GetExtremeMovers();
            result.AddRange(extremeMovers);
            List<string> allTimeRanked = LoadTrendWords();
            result.AddRange(allTimeRanked);
            cache.Add(TrendsCacheKey, result, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

        }
        else
        {
            result = cache[TrendsCacheKey] as List<string>;
        }
        return result;
    }

    public static List<string> LoadTrendWords()
    {

        Cache cache = HttpContext.Current.Cache;
        List<string> result = new List<string>();
        XmlDocument doc = new XmlDocument();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://www.live.com/?scope=web&mkt=en-US&setlang=SET_NULL&uid=12765715&FORM=W5WA");
        CookieContainer cookieContainer = new CookieContainer();
        request.CookieContainer = cookieContainer;
        request.GetResponse();
        HttpWebRequest xmlRequest = (HttpWebRequest)WebRequest.Create(LiveXrankFeedUrl);
        xmlRequest.CookieContainer = cookieContainer;
        WebResponse xmlResponse = xmlRequest.GetResponse();

        Encoding enc = Encoding.UTF8; // Windows default Code Page
        StreamReader loResponseStream = new StreamReader(xmlResponse.GetResponseStream(), enc);
        string xmlString = loResponseStream.ReadToEnd();
        doc.LoadXml(xmlString);
        foreach (XmlNode item in doc.SelectNodes("rss/channel/item"))
        {
            string keyword = item.SelectSingleNode("title").InnerText;


            bool IsKeyWordAllowed = GoogleHelper.CheckKeyWordAllowed(keyword);
            if (IsKeyWordAllowed)
            {
                TextInfo UsaTextInfo = new CultureInfo("en-US", false).TextInfo;

                string capitalized = UsaTextInfo.ToTitleCase(keyword);
                result.Add(capitalized);
                GoogleHelper.AddToTrendsArchive(capitalized);
            }
        }
        return result;
    }

    public static List<SearchResult> GetBingSearchResults(string keyword)
    {
        List<SearchResult> result;
        string feedUrl = string.Format(BingSearchFeedFormatString, keyword);
        XmlDocument xdoc = new XmlDocument();
        Cache cache = HttpContext.Current.Cache;
        if (cache[feedUrl] != null)
        {
            result = cache[feedUrl] as List<SearchResult>;
        }
        else
        {
            //try
            //{
            //    xdoc.Load(feedUrl);
            //}
            //catch (System.Xml.XmlException)
            //{
            //    // If it failed to parse, try loading the document into a string then parsing from that.
            //    string html = LoadUrl(feedUrl);
            //    XmlTextReader reader = new XmlTextReader(new StringReader(html));
            //    xdoc.Load(reader);
            //    reader.Close();
            //}
            xdoc.Load(feedUrl);
            result = new List<SearchResult>();
            foreach (XmlNode item in xdoc.SelectNodes("rss/channel/item"))
            {
                SearchResult resultToAdd = new SearchResult();
                if (item.SelectSingleNode("description")!=null)
                {
                    resultToAdd.Content = item.SelectSingleNode("description").InnerText;
                    resultToAdd.Title = item.SelectSingleNode("title").InnerText;
                    resultToAdd.Url = item.SelectSingleNode("link").InnerText;
                    result.Add(resultToAdd);
                }
                
            }            
            cache.Add(feedUrl, result, null, DateTime.Now.AddHours(2), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        return result;

    }

    private static string LoadUrl(string url)
    {
        StreamReader sr = null;
        try
        {
            HttpWebRequest myRequest = (HttpWebRequest)(System.Net.WebRequest.Create(url));
            HttpWebResponse myResponse = (HttpWebResponse)(myRequest.GetResponse());
            sr = new System.IO.StreamReader(myResponse.GetResponseStream());
            return sr.ReadToEnd();
        }
        finally
        {
            if (sr != null)
            {
                sr.Dispose();
            }
        }
    }


}
